//
//  BIDShowPhotoView.m
//  党务通
//
//  Created by mal on 13-11-21.
//  Copyright (c) 2013年 mal. All rights reserved.
//

#import "BIDShowPhotoView.h"
#import "UIImage+BIDImageScale.h"
#import "BIDGlobalMethods.h"
#import "BIDCustomSpinnerView.h"
#import "BIDScrollViewWithImage.h"

#define ZOOM_VIEW_TAG 100
#define ZOOM_STEP 1.5

@implementation BIDShowPhotoView

@synthesize addPhotoBtn;
@synthesize label;
@synthesize imgViewArray;
@synthesize photoView;
@synthesize pageControl;
@synthesize bSpeed;
@synthesize bLeftToRight;
@synthesize oldPosX;
@synthesize delegate;
@synthesize photoCount;
@synthesize bCanSave;
@synthesize bNeedScale;
@synthesize bCanDelete;
@synthesize originalImgArr;
@synthesize spinnerView;
@synthesize imageScrollView;
@synthesize lastPage;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        lastPage = 0;
        self.bSpeed = NO;
        self.bLeftToRight = NO;
        bCanSave = NO;
        bNeedScale = NO;
        bCanDelete = NO;
        imgViewArray = [[NSMutableArray alloc] initWithCapacity:3];
        originalImgArr = [[NSMutableArray alloc] initWithCapacity:1];
        [self initView];
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (void)initView
{
    self.layer.borderWidth = 1;
    self.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.layer.cornerRadius = 5;
    
    CGSize btnSize = CGSizeMake(70, 70);
    NSInteger leftSpacing = 5;
    CGRect btnFrame = CGRectMake(leftSpacing, (self.frame.size.height-btnSize.height)/2, btnSize.width, btnSize.height);
    addPhotoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addPhotoBtn setBackgroundImage:[UIImage imageNamed:@"addPhoto.png"] forState:UIControlStateNormal];
    addPhotoBtn.frame = btnFrame;
    [self addSubview:addPhotoBtn];
    
    CGSize labelSize = CGSizeMake(100, 70);
    CGRect labelFrame = CGRectMake(btnFrame.origin.x+btnFrame.size.width+5, btnFrame.origin.y, labelSize.width, labelSize.height);
    label = [[UILabel alloc] initWithFrame:labelFrame];
    label.text = @"添加图片";
    [label setBackgroundColor:[UIColor clearColor]];
    label.font = [UIFont systemFontOfSize:20];
    [self addSubview:label];
    
    //
    spinnerView = [[BIDCustomSpinnerView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
    [spinnerView initView];
}

- (void)addPhoto:(UIImage *)img
{
    self.label.hidden = YES;
    //图片之间的间隔
    NSInteger interval = 5;
    CGSize imgViewSize = CGSizeMake(70, 70);
    CGRect imgViewFrame;
    CGFloat imgViewHeight = (self.frame.size.height-imgViewSize.height)/2;
    UIImageView *imgView = nil;
    UIImageView *newImgView = nil;
    if(imgViewArray.count==0)
    {
        imgViewFrame = CGRectMake(5, imgViewHeight, imgViewSize.width, imgViewSize.height);
    }
    else
    {
        imgView = [imgViewArray objectAtIndex:(imgViewArray.count-1)];
        imgViewFrame = CGRectMake(imgView.frame.origin.x+imgView.frame.size.width+interval, imgViewHeight, imgViewSize.width, imgViewSize.height);
    }
    CGRect btnFrame = self.addPhotoBtn.frame;
    btnFrame.origin.x = imgViewFrame.origin.x + imgViewFrame.size.width + interval;
    self.addPhotoBtn.frame = btnFrame;
    
    newImgView = [[UIImageView alloc] initWithFrame:imgViewFrame];
    [newImgView setImage:img];
    [self addSubview:newImgView];
    
    newImgView.tag = [imgViewArray count];
    [self.imgViewArray addObject:newImgView];
    [originalImgArr addObject:img];
    if(imgViewArray.count==photoCount) self.addPhotoBtn.hidden = YES;
    
    //为imageView添加手势
    newImgView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imgViewTap:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [newImgView addGestureRecognizer:tap];
}

//显示照片的预览(大图片)
- (void)imgViewTap:(UITapGestureRecognizer *)sender
{
    //隐藏状态栏
    if(delegate)
    {
        [delegate changeStatusForStatusBar:0];
    }
    
    NSInteger index = sender.view.tag;
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    CGRect viewFrame = CGRectMake(0, 0, screenSize.width, screenSize.height);
    photoView = [[UIView alloc] initWithFrame:viewFrame];
    [photoView setBackgroundColor:[UIColor blackColor]];
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:photoView];
    
    CGFloat interval = 40;
    //添加滚动视图
    CGSize scrollViewSize = CGSizeMake(screenSize.width, screenSize.height-interval*2);
    CGRect scrollViewFrame = CGRectMake(0, interval, scrollViewSize.width, scrollViewSize.height);
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:scrollViewFrame];
    NSInteger count = [self.imgViewArray count];
    CGSize contentSize = CGSizeMake(scrollViewSize.width*count, scrollViewSize.height);
    scrollView.contentSize = contentSize;
    scrollView.directionalLockEnabled = YES;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.scrollEnabled = YES;
    scrollView.pagingEnabled = YES;
    scrollView.delegate = self;
    [photoView addSubview:scrollView];
    
    //把照片添加到滚动视图中
    CGSize imgViewSize = CGSizeMake(screenSize.width, screenSize.height-interval*2);
    //
    for(int i=0; i<imgViewArray.count; i++)
    {
        //创建用来放大缩小图片的scrollView,每个图片对应一个scrollView;
        BIDScrollViewWithImage *imgScrollView = [[BIDScrollViewWithImage alloc] initWithFrame:CGRectMake(i*320, 0, scrollViewSize.width, scrollViewSize.height)];
        imgScrollView.tag = 100 + i;
        //CGRect imgViewFrame = CGRectMake(i*imgViewSize.width, 0, imgViewSize.width, imgViewSize.height);
        UIImageView *temporaryImgView = [imgViewArray objectAtIndex:i];
        UIImage *img;
        if(bNeedScale)
        {
            //imgView.image = [temporaryImgView.image scaleToSize:CGSizeMake(imgViewSize.width, imgViewSize.height)];
            img = [UIImage imageCompressForSize:temporaryImgView.image targetSize:CGSizeMake(imgViewSize.width, imgViewSize.height)];
        }
        else
        {
            img = temporaryImgView.image;
        }
        [imgScrollView setImage:img];
        [scrollView addSubview:imgScrollView];
        //[scrollView addSubview:imgView];
    }
    
    //设置偏移位置
    CGPoint pos = CGPointMake(index*imgViewSize.width, 0);
    [scrollView setContentOffset:pos];
    
    //添加页控制器
    CGSize pageControlSize = CGSizeMake(screenSize.width, 40);
    CGRect pageControlFrame = CGRectMake(0, screenSize.height-pageControlSize.height, pageControlSize.width, pageControlSize.height);
    pageControl = [[UIPageControl alloc] initWithFrame:pageControlFrame];
    [pageControl setNumberOfPages:[imgViewArray count]];
    pageControl.currentPage = index;
    [photoView addSubview:pageControl];
    
    //添加删除按钮
    CGSize btnSize = CGSizeMake(58, 30);
    CGRect btnFrame = CGRectMake(screenSize.width-btnSize.width, 5, btnSize.width, btnSize.height);
    UIButton *trashBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    trashBtn.frame = btnFrame;
    [trashBtn setBackgroundImage:[UIImage imageNamed:@"trash.png"] forState:UIControlStateNormal];
    [trashBtn addTarget:self action:@selector(deletePhoto:) forControlEvents:UIControlEventTouchUpInside];
    [photoView addSubview:trashBtn];
    if(bCanDelete)
    {
        trashBtn.hidden = NO;
    }
    else
    {
        trashBtn.hidden = YES;
    }
    if(bCanSave)
    {
        trashBtn.hidden = YES;
        UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        saveBtn.frame = btnFrame;
        [saveBtn setBackgroundImage:[UIImage imageNamed:@"saveBtn.png"] forState:UIControlStateNormal];
        [saveBtn addTarget:self action:@selector(savePhoto) forControlEvents:UIControlEventTouchUpInside];
        [photoView addSubview:saveBtn];
    }
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(photoViewTap:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [photoView addGestureRecognizer:tap];
}

- (void)photoViewTap:(UITapGestureRecognizer *)sender
{
    [delegate changeStatusForStatusBar:1];
    [photoView removeFromSuperview];
}

//保存图片到相册
- (void)savePhoto
{
    spinnerView.content = @"正在保存..";
    [spinnerView showTheView];
    NSInteger index = pageControl.currentPage;
    UIImage *img = [originalImgArr objectAtIndex:index];
    UIImageWriteToSavedPhotosAlbum(img, self, @selector(savePhotoToAlbum:didFinishSavingWithError:contextInfo:), nil);
}
//保存图片的回调函数
- (void)savePhotoToAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)err contextInfo:(void *)contextInfo
{
    [spinnerView dismissTheView];
    NSString *msg = @"";
    if(err==nil)
    {
        msg = @"保存成功";
    }
    else
    {
        msg = @"保存失败";
    }
    [BIDGlobalMethods showAlertView:msg buttonTitle:@"关闭" delegate:nil tag:0];
}

- (void)deletePhoto:(UIButton *)sender
{
    NSInteger index = pageControl.currentPage;

    UIView *parentView = [sender superview];
    NSArray *subViewsArr = [parentView subviews];
    UIScrollView *scrollView;
    for(int i=0; i<subViewsArr.count; i++)
    {
        if([[subViewsArr objectAtIndex:i] isKindOfClass:[UIScrollView class]])
        {
            scrollView = [subViewsArr objectAtIndex:i];
        }
    }
    //从预览视图中移除
    UIImageView *imgView = nil;
    NSArray *arr = [scrollView subviews];
    imgView = [arr objectAtIndex:index];
    [imgView removeFromSuperview];
    //重新设置滚动视图的内容大小
    CGSize scrollViewSize = scrollView.contentSize;
    scrollViewSize.width -= scrollView.frame.size.width;
    scrollView.contentSize = scrollViewSize;
    //重新调整滚动视图中子视图的位置
    for(int i=((int)index+1); i<arr.count; i++)
    {
        imgView = [arr objectAtIndex:i];
        CGRect frame = imgView.frame;
        frame.origin.x -= scrollView.frame.size.width;
        imgView.frame = frame;
    }
    //调整页控制器
    [pageControl setNumberOfPages:([pageControl numberOfPages]-1)];
    if([pageControl numberOfPages]>0)
    {
        pageControl.currentPage = index;
    }
    
    //从视图展示视图中移除
    //图片之间的间隔
    NSInteger interval = 5;
    UIImageView *preImgView = [imgViewArray objectAtIndex:index];
    [preImgView removeFromSuperview];
    for(int i=(int)index+1; i<imgViewArray.count; i++)
    {
        imgView = [imgViewArray objectAtIndex:i];
        preImgView = [imgViewArray objectAtIndex:i-1];
        if(i==index+1)
        {
            imgView.frame = preImgView.frame;
        }
        else
        {
            CGRect frame = imgView.frame;
            frame.origin.x = preImgView.frame.origin.x + preImgView.frame.size.width + interval;
        }
        imgView.tag = i-1;
    }
    
    //从数组中删除图片
    [imgViewArray removeObjectAtIndex:index];
    [originalImgArr removeObjectAtIndex:index];
    
    //设置添加图片的按钮
    addPhotoBtn.hidden = NO;
    CGRect frame = addPhotoBtn.frame;
    if(imgViewArray.count==0)
    {
        frame.origin.x = 5;
        addPhotoBtn.frame = frame;
        [[UIApplication sharedApplication] setStatusBarHidden:NO];
        [photoView removeFromSuperview];
    }
    else
    {
        imgView = [imgViewArray objectAtIndex:[imgViewArray count]-1];
        frame.origin.x = imgView.frame.origin.x + imgView.frame.size.width + interval;
        addPhotoBtn.frame = frame;
    }
}

#pragma mark UIScrollViewDelegate
//ScrollView 划动的动画结束后调用.
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
	CGFloat pageWidth = scrollView.frame.size.width;
	NSInteger page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
	//NSLog(@"page = %d, lastPage = %d", page, lastPage);
	pageControl.currentPage = page;
	if (lastPage != page)
	{
		BIDScrollViewWithImage *aView = (BIDScrollViewWithImage *)[scrollView viewWithTag:100+lastPage];
		aView.zoomScale = 1.0;
		
		lastPage = page;
	}
}
//- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
//{
//    oldPosX = scrollView.contentOffset.x;
//}
//
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    if(bSpeed)
//    {
//        CGSize scrollViewSize = scrollView.frame.size;
//        NSInteger count = scrollView.contentOffset.x / scrollViewSize.width;
//        CGPoint pos;
//        if(!bLeftToRight)
//        {
//            if(count<imgViewArray.count-1)
//            {
//                pos = CGPointMake((count+1)*scrollViewSize.width, 0);
//                pageControl.currentPage = count+1;
//            }
//            else
//            {
//                pos = CGPointMake(count*scrollViewSize.width, 0);
//            }
//        }
//        else
//        {
//            if(count>1)
//            {
//                pos = CGPointMake((count-1)*scrollViewSize.width, 0);
//                pageControl.currentPage = count-1;
//            }
//            else
//            {
//                pos = CGPointMake(count*scrollViewSize.width, 0);
//                pageControl.currentPage = count;
//            }
//        }
//        [scrollView setContentOffset:pos animated:YES];
//        bSpeed = NO;
//    }
//}
//
//- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
//{
//    if(scrollView != imageScrollView) return;
//    if(oldPosX<scrollView.contentOffset.x)
//    {
//        bLeftToRight = NO;
//    }
//    else
//    {
//        bLeftToRight = YES;
//    }
//    CGSize scrollViewSize = scrollView.frame.size;
//    NSInteger count = scrollView.contentOffset.x / scrollViewSize.width;
//    CGPoint pos;
//    if(decelerate)
//    {
//        bSpeed = YES;
//    }
//    else
//    {
//        if(scrollViewSize.width/2 < fmodf(scrollView.contentOffset.x, scrollViewSize.width))
//        {
//            pos = CGPointMake((count+1)*scrollViewSize.width, 0);
//            pageControl.currentPage = count+1;
//        }
//        else
//        {
//            pos = CGPointMake(count*scrollViewSize.width, 0);
//            pageControl.currentPage = count;
//        }
//        [scrollView setContentOffset:pos animated:YES];
//    }
//}
@end
